#define _CRT_SECURE_NO_WARNINGS
#include"Queue.h"

void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

void QueueDestroy(Queue* pq)
{
	assert(pq);
	QueueNode* pur = pq->phead;
	while (pur)
	{
		QueueNode* next = pur->next;
		free(pur);
		pur = next;
	}
	pq->phead = pq->ptail = NULL;
	pq->size=0;
}

void QueuePush(Queue* pq, QDatatype x) 
{
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (!newnode)
	{
		perror("malloc fail!");
		exit(1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (!pq->phead)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	++pq->size;
}



bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead == NULL;
}
		                                                       

void QueuePop(Queue* pq)
{
	assert(!QueueEmpty(pq));
	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		QueueNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	--pq->size;
}

QDatatype QueueFront(Queue* pq)
{
	assert(pq);
	return pq->phead->data;
}

QDatatype QueueBack(Queue* pq)
{
	assert(pq);
	return pq->ptail->data;
}


int QueueSize(Queue* pq)
{
	assert(pq);
	QueueNode* pur = pq->phead;
	int size = 0;
	while (pur)
	{
		pur = pur->next;
		size++;
	}
	return size;
}
